<template>
  <div class="template-form-renderer">
    <el-form
      ref="formRef"
      :model="formData"
      label-width="150px"
      :disabled="readonly"
    >
      <!-- 遍历所有字段组 -->
      <el-card
        v-for="group in fieldsConfig"
        :key="group.group"
        class="form-group-card"
        shadow="never"
      >
        <template #header>
          <div class="card-header">
            <el-icon v-if="getGroupIcon(group.group)" class="group-icon">
              <component :is="getGroupIcon(group.group)" />
            </el-icon>
            <span class="group-title">{{ group.groupLabel }}</span>
          </div>
        </template>

        <!-- 遍历组内字段 -->
        <div
          v-for="field in group.fields"
          :key="field.path"
          class="form-field"
          v-show="shouldShowField(field)"
        >
          <!-- 文本输入框 -->
          <el-form-item
            v-if="field.type === 'text' || field.type === 'input'"
            :label="field.label"
            :required="field.required"
            :prop="field.path"
          >
            <el-input
              v-model="formData[field.path]"
              :placeholder="field.placeholder"
              :type="field.inputType || 'text'"
              :disabled="readonly"
              @input="handleFieldChange"
            >
              <!-- 插入变量按钮（仅在启用变量插入时显示） -->
              <template #append v-if="enableVariableInsertion && !readonly">
                <el-button
                  @click="handleInsertVariable(field.path)"
                  :icon="Link"
                  title="插入变量引用"
                >
                  插入变量
                </el-button>
              </template>
            </el-input>
            <div v-if="field.desc" class="field-desc">
              <el-icon><InfoFilled /></el-icon>
              {{ field.desc }}
            </div>
          </el-form-item>

          <!-- 带前缀的输入框（旧版，保留兼容性） -->
          <el-form-item
            v-else-if="field.type === 'prefix-input'"
            :label="field.label"
            :required="field.required"
            :prop="field.path"
          >
            <PrefixInput
              v-model="formData[field.path]"
              :prefix="getFieldPrefix(field)"
              :placeholder="field.placeholder"
              :readonly="readonly"
              @change="handleFieldChange"
            />
            <div v-if="field.desc" class="field-desc">
              <el-icon><InfoFilled /></el-icon>
              {{ field.desc }}
            </div>
          </el-form-item>

          <!-- 拆分路径输入框（前缀只读 + 用户输入） -->
          <el-form-item
            v-else-if="field.type === 'split-path-input'"
            :label="field.label"
            :required="field.required"
            :prop="field.path"
          >
            <SplitPathInput
              v-model="formData[field.path]"
              :prefix="getFieldPrefix(field)"
              :placeholder="field.placeholder"
              :readonly="readonly"
              @change="handleFieldChange"
            />
            <div v-if="field.desc" class="field-desc">
              <el-icon><InfoFilled /></el-icon>
              {{ field.desc }}
            </div>
          </el-form-item>

          <!-- 单选框 -->
          <el-form-item
            v-else-if="field.type === 'radio'"
            :label="field.label"
            :required="field.required"
            :prop="field.path"
          >
            <el-radio-group
              v-model="formData[field.path]"
              :disabled="readonly"
              @change="handleFieldChange"
            >
              <el-radio
                v-for="option in field.options"
                :key="option.value"
                :value="option.value"
              >
                {{ option.label }}
              </el-radio>
            </el-radio-group>
          </el-form-item>

          <!-- 下拉选择框 -->
          <el-form-item
            v-else-if="field.type === 'select'"
            :label="field.label"
            :required="field.required"
            :prop="field.path"
          >
            <el-select
              v-model="formData[field.path]"
              :placeholder="field.placeholder"
              :disabled="readonly"
              @change="handleFieldChange"
              style="width: 100%"
            >
              <el-option
                v-for="option in field.options"
                :key="option.value"
                :label="option.label"
                :value="option.value"
              />
            </el-select>
            <div v-if="field.desc" class="field-desc">
              <el-icon><InfoFilled /></el-icon>
              {{ field.desc }}
            </div>
          </el-form-item>

          <!-- OBS配置选择框 -->
          <el-form-item
            v-else-if="field.type === 'select-obs'"
            :label="field.label"
            :required="field.required"
            :prop="field.path"
          >
            <el-select
              v-model="formData[field.path]"
              :placeholder="field.placeholder"
              :disabled="readonly"
              clearable
              @change="(value) => handleObsPresetChange(value, field)"
              style="width: 100%"
            >
              <el-option
                v-for="preset in filteredObsPresets"
                :key="preset.id"
                :label="preset.name"
                :value="preset.id"
              >
                <span>{{ preset.name }}</span>
                <el-text type="info" size="small" style="margin-left: 8px">{{ preset.bucket_id }}</el-text>
              </el-option>
            </el-select>
            <div v-if="field.desc" class="field-desc">
              <el-icon><InfoFilled /></el-icon>
              {{ field.desc }}
            </div>
          </el-form-item>

          <!-- 镜像配置选择框 -->
          <el-form-item
            v-else-if="field.type === 'select-image'"
            :label="field.label"
            :required="field.required"
            :prop="field.path"
          >
            <el-select
              v-model="formData[field.path]"
              :placeholder="field.placeholder"
              :disabled="readonly"
              clearable
              @change="handleImagePresetChange"
              style="width: 100%"
            >
              <el-option
                v-for="preset in filteredImagePresets"
                :key="preset.id"
                :label="preset.name"
                :value="preset.id"
              />
            </el-select>
            <div v-if="field.desc" class="field-desc">
              <el-icon><InfoFilled /></el-icon>
              {{ field.desc }}
            </div>
          </el-form-item>

          <!-- 资源池配置选择框 -->
          <el-form-item
            v-else-if="field.type === 'select-resource'"
            :label="field.label"
            :required="field.required"
            :prop="field.path"
          >
            <el-select
              v-model="formData[field.path]"
              :placeholder="field.placeholder"
              :disabled="readonly"
              clearable
              @change="handleResourcePresetChange"
              style="width: 100%"
            >
              <el-option
                v-for="preset in filteredResourcePresets"
                :key="preset.id"
                :label="preset.name"
                :value="preset.id"
              >
                <span>{{ preset.name }}</span>
                <el-text type="info" size="small" style="margin-left: 8px">{{ preset.pool_type }}</el-text>
              </el-option>
            </el-select>
            <div v-if="field.desc" class="field-desc">
              <el-icon><InfoFilled /></el-icon>
              {{ field.desc }}
            </div>
          </el-form-item>

          <!-- NAS配置选择框 -->
          <el-form-item
            v-else-if="field.type === 'select-nas'"
            :label="field.label"
            :required="field.required"
            :prop="field.path"
          >
            <el-select
              v-model="formData[field.path]"
              :placeholder="field.placeholder"
              :disabled="readonly"
              clearable
              @change="handleFieldChange"
              style="width: 100%"
            >
              <el-option
                v-for="preset in filteredNasPresets"
                :key="preset.id"
                :label="preset.name"
                :value="preset.id"
              >
                <span>{{ preset.name }}</span>
              </el-option>
            </el-select>
            <div v-if="field.desc" class="field-desc">
              <el-icon><InfoFilled /></el-icon>
              {{ field.desc }}
            </div>
          </el-form-item>

          <!-- 开关按钮 -->
          <el-form-item
            v-else-if="field.type === 'switch'"
            :label="field.label"
            :required="field.required"
            :prop="field.path"
          >
            <el-switch
              :model-value="getSwitchValue(field)"
              @change="(value) => handleSwitchChange(value, field)"
              :disabled="readonly"
              :active-text="field.switchValues?.on === true ? '开启' : (field.switchValues?.on || '是')"
              :inactive-text="field.switchValues?.off === false ? '关闭' : (field.switchValues?.off || '否')"
            />
            <div v-if="field.desc" class="field-desc">
              <el-icon><InfoFilled /></el-icon>
              {{ field.desc }}
            </div>
          </el-form-item>

          <!-- 键值对输入（对象类型）-->
          <el-form-item
            v-else-if="field.type === 'keyvalue' && !field.isArray"
            :label="field.label"
            :required="field.required"
            :prop="field.path"
            class="keyvalue-field"
          >
            <template #label>
              <span>{{ field.label }}</span>
              <el-button
                v-if="!readonly"
                type="primary"
                size="small"
                text
                @click="addKeyValuePair(field.path)"
              >
                <el-icon><Plus /></el-icon>
                添加
              </el-button>
            </template>
            <div class="keyvalue-list">
              <div
                v-for="(entry, index) in getKeyValueEntries(field.path)"
                :key="`kv-${field.path}-${index}`"
                class="keyvalue-item"
              >
                <el-input
                  :model-value="entry.key"
                  :placeholder="field.placeholder?.key || '键'"
                  :disabled="readonly"
                  @input="(newKey) => updateKeyValueKey(field.path, entry.key, newKey)"
                  style="width: 35%"
                />
                <span class="equal-sign">=</span>
                <el-input
                  v-model="formData[field.path][entry.key]"
                  :placeholder="field.placeholder?.value || '值'"
                  :disabled="readonly"
                  @input="handleFieldChange"
                  style="width: 35%"
                />
                <el-button
                  v-if="enableVariableInsertion && !readonly"
                  type="primary"
                  size="small"
                  text
                  @click="handleInsertVariable(`${field.path}.${entry.key}`)"
                  :icon="Link"
                  title="插入变量"
                >
                  变量
                </el-button>
                <el-button
                  v-if="!readonly"
                  type="danger"
                  size="small"
                  text
                  @click="removeKeyValuePair(field.path, entry.key)"
                >
                  <el-icon><Delete /></el-icon>
                </el-button>
              </div>
              <div v-if="field.desc" class="field-desc">
                <el-icon><InfoFilled /></el-icon>
                {{ field.desc }}
              </div>
            </div>
          </el-form-item>

          <!-- 键值对输入（数组类型，如 params）-->
          <el-form-item
            v-else-if="field.type === 'keyvalue' && field.isArray"
            :label="field.label"
            :required="field.required"
            :prop="field.path"
            class="keyvalue-field"
          >
            <template #label>
              <span>{{ field.label }}</span>
              <el-button
                v-if="!readonly"
                type="primary"
                size="small"
                text
                @click="addArrayKeyValuePair(field.path, field.arrayItemStructure)"
              >
                <el-icon><Plus /></el-icon>
                添加
              </el-button>
            </template>
            <div class="keyvalue-list">
              <div
                v-for="(item, index) in formData[field.path]"
                :key="`kv-array-${field.path}-${index}`"
                class="keyvalue-item"
              >
                <el-input
                  v-model="item.key"
                  :placeholder="field.placeholder?.key || '键'"
                  :disabled="readonly"
                  @input="handleFieldChange"
                  style="width: 35%"
                />
                <span class="equal-sign">=</span>
                <el-input
                  v-model="item.value"
                  :placeholder="field.placeholder?.value || '值'"
                  :disabled="readonly"
                  @input="handleFieldChange"
                  style="width: 35%"
                />
                <el-button
                  v-if="enableVariableInsertion && !readonly"
                  type="primary"
                  size="small"
                  text
                  @click="handleInsertVariable(`${field.path}[${index}].value`)"
                  :icon="Link"
                  title="插入变量"
                >
                  变量
                </el-button>
                <el-button
                  v-if="!readonly"
                  type="danger"
                  size="small"
                  text
                  @click="removeArrayKeyValuePair(field.path, index)"
                >
                  <el-icon><Delete /></el-icon>
                </el-button>
              </div>
              <div v-if="field.desc" class="field-desc">
                <el-icon><InfoFilled /></el-icon>
                {{ field.desc }}
              </div>
            </div>
          </el-form-item>
        </div>
      </el-card>
    </el-form>
  </div>
</template>

<script setup>
import { ref, watch, nextTick, computed } from 'vue';
import {
  Document,
  Setting,
  Upload,
  Folder,
  Box,
  Monitor,
  Plus,
  Delete,
  InfoFilled,
  Link,
  Notebook,
  Tools,
  Connection,
} from '@element-plus/icons-vue';
import { FIELD_GROUPS } from '@/config/templateFieldsConfig';
import PrefixInput from '@/components/PrefixInput/index.vue';
import SplitPathInput from '@/components/SplitPathInput/index.vue';
import { getValueByPath, setValueByPath } from '@/utils/yamlTemplateParser';

const props = defineProps({
  modelValue: {
    type: Object,
    required: true,
  },
  fieldsConfig: {
    type: Array,
    required: true,
  },
  readonly: {
    type: Boolean,
    default: false,
  },
  enableVariableInsertion: {
    type: Boolean,
    default: false,
  },
  // 当前选中的应用ID
  selectedApplicationId: {
    type: [Number, String],
    default: null,
  },
  // OBS配置预设列表
  obsPresets: {
    type: Array,
    default: () => [],
  },
  // 镜像配置预设列表
  imagePresets: {
    type: Array,
    default: () => [],
  },
  // 资源池配置预设列表
  resourcePresets: {
    type: Array,
    default: () => [],
  },
  // NAS配置预设列表
  nasPresets: {
    type: Array,
    default: () => [],
  },
});

const emit = defineEmits(['update:modelValue', 'change', 'insert-variable']);

const formRef = ref(null);
const formData = ref(props.modelValue);

// 根据应用ID筛选配置预设
const filteredObsPresets = computed(() => {
  if (!props.selectedApplicationId) return props.obsPresets;
  return props.obsPresets.filter(p => p.application_id === props.selectedApplicationId);
});

const filteredImagePresets = computed(() => {
  if (!props.selectedApplicationId) return props.imagePresets;
  return props.imagePresets.filter(p => p.application_id === props.selectedApplicationId);
});

const filteredResourcePresets = computed(() => {
  if (!props.selectedApplicationId) return props.resourcePresets;
  return props.resourcePresets.filter(p => p.application_id === props.selectedApplicationId);
});

const filteredNasPresets = computed(() => {
  if (!props.selectedApplicationId) return props.nasPresets;
  return props.nasPresets.filter(p => p.application_id === props.selectedApplicationId);
});

// 监听外部数据变化
watch(
  () => props.modelValue,
  (newVal) => {
    formData.value = newVal;
  },
  { deep: true }
);

// 监听内部数据变化，触发更新
watch(
  formData,
  (newVal) => {
    emit('update:modelValue', newVal);
    emit('change', newVal);
  },
  { deep: true }
);

// 判断字段是否应该显示（基于依赖条件）
function shouldShowField(field) {
  if (!field.dependsOn) return true;

  // 【关键修复】formData 是扁平化结构，直接使用 dependsOn 作为键
  const dependValue = formData.value[field.dependsOn];
  return dependValue === field.dependsOnValue;
}

// 获取嵌套值
function getNestedValue(obj, path) {
  return getValueByPath(obj, path);
}

// 设置嵌套值
function setNestedValue(obj, path, value) {
  setValueByPath(obj, path, value);
}

// 获取前缀输入框的前缀
function getFieldPrefix(field) {
  if (!field.prefixPath) return '';
  // 【关键修复】formData 是扁平化结构，直接使用 prefixPath 作为键
  return formData.value[field.prefixPath] || '';
}

// 获取开关的值
function getSwitchValue(field) {
  // 【关键修复】formData 是扁平化结构，直接使用 field.path 作为键
  const value = formData.value[field.path];
  if (field.switchValues) {
    return value === field.switchValues.on;
  }
  return !!value;
}

// 处理开关变化
function handleSwitchChange(checked, field) {
  let value;
  if (field.switchValues) {
    value = checked ? field.switchValues.on : field.switchValues.off;
  } else {
    value = checked;
  }
  formData.value[field.path] = value;
}

// 处理OBS配置预设选择
function handleObsPresetChange(presetId, field) {
  if (!presetId) {
    handleFieldChange();
    return;
  }

  const preset = props.obsPresets.find(p => p.id === presetId);
  if (!preset) return;

  // 根据obsUsage判断填充哪些字段
  // 只填充前缀(prefix)和桶ID，不直接修改完整路径
  if (field.obsUsage === 'code') {
    // 代码配置
    formData.value['config.appUrlBucketId'] = preset.bucket_id;
    formData.value['config.appUrlPrefix'] = preset.bucket_name || preset.bucket_path;
    // 不修改 config.appUrlUserInput，保留用户输入
  } else if (field.obsUsage === 'output') {
    // 输出配置
    formData.value['config.outputs[0].obsBucketUid'] = preset.bucket_id;
    formData.value['config.outputs[0].obsUrlPrefix'] = preset.bucket_name || preset.bucket_path;
    // 不修改 config.outputs[0].obsUrlUserInput，保留用户输入
  } else if (field.obsUsage === 'log') {
    // 日志配置
    formData.value['config.logUrlBucketId'] = preset.bucket_id;
    formData.value['config.logUrlPrefix'] = preset.bucket_name || preset.bucket_path;
    // 不修改 config.logUrlUserInput，保留用户输入
  }

  handleFieldChange();
}

// 处理镜像配置预设选择
function handleImagePresetChange(presetId) {
  if (!presetId) {
    handleFieldChange();
    return;
  }

  const preset = props.imagePresets.find(p => p.id === presetId);
  if (!preset) return;

  formData.value['config.userImageUid'] = preset.image_uid;
  formData.value['config.userImageVersionUid'] = preset.image_version_uid;

  handleFieldChange();
}

// 处理资源池配置预设选择
function handleResourcePresetChange(presetId) {
  if (!presetId) {
    handleFieldChange();
    return;
  }

  const preset = props.resourcePresets.find(p => p.id === presetId);
  if (!preset) return;

  formData.value['config.poolType'] = preset.pool_type;
  formData.value['config.poolUid'] = preset.pool_uid;
  formData.value['config.specName'] = preset.spec_name;
  formData.value['config.flavorCode'] = preset.flavor_code;

  handleFieldChange();
}

// 字段值变化处理
function handleFieldChange() {
  nextTick(() => {
    emit('update:modelValue', formData.value);
    emit('change', formData.value);
  });
}

// 获取分组图标
function getGroupIcon(groupId) {
  const iconMap = {
    basic: Document,
    config: Setting,
    outputs: Upload,
    code: Folder,
    image: Box,
    resource: Monitor,
    dynamic: Plus,
    log: Notebook,
    other: Setting,
    advanced: Tools,
    nas_warmup: Connection,
  };
  return iconMap[groupId];
}

// 处理插入变量
function handleInsertVariable(fieldPath) {
  emit('insert-variable', fieldPath);
}

// 获取键值对条目数组（用于稳定的key绑定）
function getKeyValueEntries(path) {
  const obj = formData.value[path];
  if (!obj || typeof obj !== 'object' || Array.isArray(obj)) {
    return [];
  }
  return Object.entries(obj).map(([key, value]) => ({ key, value }));
}

// 添加键值对（对象类型）
function addKeyValuePair(path) {
  if (!formData.value[path]) {
    formData.value[path] = {};
  }

  const newKey = `NEW_KEY_${Date.now()}`;
  formData.value[path][newKey] = '';
  handleFieldChange();
}

// 更新键值对的键名
function updateKeyValueKey(path, oldKey, newKey) {
  if (oldKey === newKey) return;
  if (!formData.value[path]) return;

  const value = formData.value[path][oldKey];
  delete formData.value[path][oldKey];
  formData.value[path][newKey] = value;
  handleFieldChange();
}

// 删除键值对（对象类型）
function removeKeyValuePair(path, key) {
  if (formData.value[path]) {
    delete formData.value[path][key];
    handleFieldChange();
  }
}

// 添加键值对（数组类型）
function addArrayKeyValuePair(path, structure) {
  if (!formData.value[path]) {
    formData.value[path] = [];
  }

  formData.value[path].push({ ...structure });
  handleFieldChange();
}

// 删除键值对（数组类型）
function removeArrayKeyValuePair(path, index) {
  if (formData.value[path]) {
    formData.value[path].splice(index, 1);
    handleFieldChange();
  }
}

// 表单验证
function validate() {
  return formRef.value?.validate();
}

// 重置表单
function resetFields() {
  formRef.value?.resetFields();
}

// 暴露方法给父组件
defineExpose({
  validate,
  resetFields,
});
</script>

<style scoped lang="scss">
.template-form-renderer {
  width: 100%;
  height: 100%;
  padding: 0;

  .form-group-card {
    margin-bottom: 20px;
    border: 1px solid #e4e7ed;

    &:first-child {
      margin-top: 0;
    }

    &:last-child {
      margin-bottom: 0;
    }

    .card-header {
      display: flex;
      align-items: center;
      font-weight: 600;
      font-size: 16px;

      .group-icon {
        margin-right: 8px;
        font-size: 18px;
        color: #409eff;
      }

      .group-title {
        color: #303133;
      }
    }

    :deep(.el-card__body) {
      padding: 20px;
    }
  }

  .form-field {
    margin-bottom: 0;

    .field-desc {
      margin-top: 4px;
      font-size: 12px;
      color: #909399;
      display: flex;
      align-items: center;
      gap: 4px;

      .el-icon {
        font-size: 14px;
      }
    }

    &:last-child {
      :deep(.el-form-item) {
        margin-bottom: 0;
      }
    }
  }

  .keyvalue-field {
    :deep(.el-form-item__label) {
      display: flex;
      align-items: center;
      justify-content: space-between;
      width: 150px;
    }

    .keyvalue-list {
      width: 100%;

      .keyvalue-item {
        display: flex;
        align-items: center;
        gap: 8px;
        margin-bottom: 12px;

        .equal-sign {
          color: #909399;
          font-weight: bold;
        }

        &:last-child {
          margin-bottom: 0;
        }
      }
    }
  }

  :deep(.el-form-item) {
    margin-bottom: 22px;
  }

  :deep(.el-input__inner) {
    font-size: 14px;
  }

  :deep(.el-radio) {
    margin-right: 20px;
  }
}
</style>
